package com.pine.dcts.log;

import com.pine.dcts.websocket.SendMessageEvent;
import com.pine.dcts.websocket.WebSocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xiaoyuan
 * @create 2021/1/13 15:56
 **/
@Slf4j
public class JobLogReader implements Runnable {

    private Integer lineLength = 0;

    private ApplicationContext applicationContext;

    private boolean end;

    private String key;

    boolean first = true;

    public JobLogReader(Integer lineLength, String key,ApplicationContext applicationContext){
       this.lineLength = lineLength;
       this.applicationContext = applicationContext;
       this.end = false;
       this.key = key;
    }

    @Override
    public void run() {
        while (!end) {
            BufferedReader reader = null;
            try {
                //日志文件路径，获取最新的
                String filePath = "D:\\Users\\cechealth\\temp\\logs\\job\\24.log.2021-01-13.log";

                //字符流
                reader = new BufferedReader(new FileReader(filePath));
                Object[] lines = reader.lines().toArray();

                //只取从上次之后产生的日志
                Object[] copyOfRange = Arrays.copyOfRange(lines, lineLength, lines.length);

                //对日志进行着色，更加美观  PS：注意，这里要根据日志生成规则来操作
                for (int i = 0; i < copyOfRange.length; i++) {
                    String line = (String) copyOfRange[i];
                    //先转义
                    line = line.replaceAll("&", "&amp;")
                            .replaceAll("<", "&lt;")
                            .replaceAll(">", "&gt;")
                            .replaceAll("\"", "&quot;");

                    //处理等级
                    line = line.replace("DEBUG", "<span style='color: blue;'>DEBUG</span>");
                    line = line.replace("INFO", "<span style='color: green;'>INFO</span>");
                    line = line.replace("WARN", "<span style='color: orange;'>WARN</span>");
                    line = line.replace("ERROR", "<span style='color: red;'>ERROR</span>");

                    //处理类名
//                    String[] split = line.split("]");
//                    if (split.length >= 2) {
//                        String[] split1 = split[1].split("-");
//                        if (split1.length >= 2) {
//                            line = split[0] + "]" + "<span style='color: #298a8a;'>" + split1[0] + "</span>" + "-" + split1[1];
//                        }
//                    }

                    // 匹配日期开头加换行，2019-08-12 14:15:04
                    Pattern r = Pattern.compile("[\\d+][\\d+][\\d+][\\d+]-[\\d+][\\d+]-[\\d+][\\d+] [\\d+][\\d+]:[\\d+][\\d+]:[\\d+][\\d+]");
                    Matcher m = r.matcher(line);
                    if (m.find( )) {
                        //找到下标
                        int start = m.start();
                        //插入
                        StringBuilder  sb = new StringBuilder (line);
                        sb.insert(start,"<br/><br/>");
                        line = sb.toString();
                    }

                    copyOfRange[i] = line;

                    System.out.println(line);
                }

                //存储最新一行开始
                lineLength = lines.length;

                //第一次如果太大，截取最新的200行就够了，避免传输的数据太大
                if(first && copyOfRange.length > 200){
                    copyOfRange = Arrays.copyOfRange(copyOfRange, copyOfRange.length - 200, copyOfRange.length);
                    first = false;
                }

                String result = StringUtils.join(copyOfRange, "<br/>");

                //发送
              //  send(session, result);

                //applicationContext.publishEvent(new SendMessageEvent(new WebSocketMessage(result,key)));

                System.out.println(result);

                //休眠一秒
                Thread.sleep(1000);
            } catch (Exception e) {
                //捕获但不处理
                e.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
        log.info("LoggingWebSocketServer 任务结束");
    }
}
